const utils = require('../../../../common/util/util')

const app = getApp()

Page({
  data: {
    posts: {},
    xSaveShowState: false,
    input: '',
    xDefaultValue: '',
    tielike: false,
    operate: false,
    xUserInfo: '',
    utu: '',
    startX: 0 ,
    startY: 0 ,
    startXs: 0 ,
    startYs: 0 ,
    totalcomment:0,
    sendbox:false,
    isLike:false
  },
  onShareAppMessage: function () {
    return {
      title: "快来看看吧~",
      path:'/subtool/pages/community/detail/index?id='+this.data.id
    };
  },
  onLoad: async function (options) {
    wx.showLoading({
      title: '加载中',
    })
    let that = this
    let id = options.id
    that.setData({
      id: id
    })
    await that.xInit(id)
    await that.xUser()
  },
  xChildReload: function () {
    var pages = getCurrentPages();//当前页面栈
    if (pages.length > 1) {
      var beforePage = pages[pages.length - 2];//获取上一个页面实例对象
      console.log(beforePage)
      // if(beforePage.navbarInitTop){
        beforePage.xParReload();//触发父页面中的方法
      // }
    }
  },
  sendboxhide:function(){
    this.setData({
      sendbox:false
    })
  },
  xInit: function (id) {
    let that = this
    wx.cloud.callFunction({
      name: 'dynamic_content',
      data: {
        action: "get_new_dynamic_content_info",
        _id: id
      }
    }).then(res => {
      let data = res.result
      data.release_time = utils.formatTime_emotion(new Date(data.release_time))
      if(that.data.totalcomment){
      }else{
        that.setData({
          totalcomment: data.comment_count
        })
      }
      for (var i in data.comment_content) {
        data.comment_content[i].comment_time = utils.formatTime_emotion(new Date(data.comment_content[i].create_time))
        data.comment_content[i].isTouchMove = false
        for(var k in data.comment_content[i].sed_comments){
          data.comment_content[i].sed_comments[k].comment_time = utils.formatTime_emotion(new Date(data.comment_content[i].sed_comments[k].create_time))
          data.comment_content[i].sed_comments[k].move = false
        }
      }
      if (data.is_thumbs_up === true) {
        that.setData({
          tielike: true
        })
      }else{
        that.setData({
          tielike: false
        })
      }
      that.setData({
        posts: data
      })
      wx.hideLoading()
    }).catch(err=>{
      wx.hideLoading()
      wx.showToast({
        title: '帖子跑丢啦~',
        icon:'none'
      })
    })
  },

  xTieLike: function () {
    let that = this
    let id = that.data.id
    let tielike = that.data.tielike
    let _id = id
    if(that.data.isLike){
      return
    }
    that.setData({
      isLike:true
    })
    let _data = {
      is_thumbs_up: !tielike,
    }
    if(_data.is_thumbs_up){
      that.setData({
          ['posts.thumbs_ups_count']:Number(that.data.posts.thumbs_ups_count)+1
      })
    }else{
      that.setData({
        ['posts.thumbs_ups_count']:Number(that.data.posts.thumbs_ups_count)-1
      })
    }
    wx.cloud.callFunction({
      name: 'dynamic_content',
      data: {
        action: "thumbs_up",
       _id: _id, //当前内容帖子ID
      }
    }).then(res => {
      that.setData({
        tielike: !tielike,
        isLike:false
      })
      that.xChildReload()
    })
    // wx.cloud.callFunction({
    //   name: 'dynamic_content',
    //   data: {
    //     action: "thumbs_up",
    //     _id: id,
    //   }
    // }).then(res => {
    //   that.setData({
    //     tielike: !tielike
    //   })
    // })
  },

  xSaveShowStateFocus: function () {
    this.setData({
      xSaveShowState: true,
      focus:true
    })
  },

  xSaveShowStateBlur: function (e) {
    let value = e.detail.value
    this.setData({
      focus:false
    })
    if (value === '') {
      this.setData({
        xSaveShowState: false
      })
    }
  },

  xLike: function (e) {
    let that = this
    let id = that.data.id
    let params = e.currentTarget.dataset
    console.log(that.data.isLike)
    if(that.data.isLike){
      return
    }
    that.setData({
      isLike:true
    })
    wx.cloud.callFunction({
      name: 'dynamic_content',
      data: {
        action: "add_comment_thumbs_up",
        content_id: id,
        comment_id: params.id
      }
    }).then(res => {
      if (!params.state) {
        wx.showToast({
          title: '点赞成功',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: '取消成功',
          icon: 'none'
        })
      }
      that.xChildReload()
      that.xInit(id)
      that.setData({
        isLike:false
      })
    })
  },

  xPreviewImage: function (e) {
    let that = this
    let path = e.currentTarget.dataset.path
    let ximg = that.data.posts.files
    wx.previewImage({
      current: path, // 当前显示图片的http链接
      urls: ximg // 需要预览的图片http链接列表
    })
  },

  xInput: function (e) {
    let that = this
    let value = e.detail.value
    that.setData({
      input: value
    })
  },

  xSave: function () {
    let that = this
    let value = that.data.input
    let id = that.data.posts._id
    let user = app.globalData.xCustomer
    let operate = app.globalData.operate
    wx.cloud.callFunction({
      name: 'dynamic_content',
      data: {
        action: "add_comment",
        _id: id,
        content: value,
        user_info: {
          avatarUrl: user.avatarUrl,
          nickName: user.nickName
        },
        //  fictitious_openid : operate === false ? '' : operate._openid
        fictitious_openid: ''
      }
    }).then(res => {
      console.log("返回1:", res.result)
      wx.showLoading({
        title: '发送中',
        success: () => {
          that.setData({
            xSaveShowState: false,
            xDefaultValue: ''
          })
        }
      })
      that.xChildReload()
      this.xInit(id)
    })
  },
  
  xInfo: function () {
    let that = this
    wx.cloud.callFunction({
      name: 'user',
      data: {
        action: 'detail'
      }
    }).then(res => {
      let user = res.result
      that.setData({
        xUserInfo: user
      })
      that.xChildReload()
    })
  },
  xUser: function () {
    let that = this
    wx.cloud.callFunction({
      name: 'user',
      data: {
        action: 'detail'
      }
    }).then(res => {
      let user = res.result
      that.setData({
        xUserInfo: user
      })
    })
  },
  xUtu: function (e) {
    let that = this
    let value = e.detail.value
    that.setData({
      utu: value
    })
  },

  xToThisMessage: function (e) {
    let that = this
    let id = e.currentTarget.dataset.id
    that.setData({
      uid: id,
      sendbox:true
    })
  },

  xToThisMessageSub: function (e) {
    let that = this
    let id = that.data.id
    let pid = e.currentTarget.dataset.id
    let name = that.data.xUserInfo.nickName
    let ava = that.data.xUserInfo.avatarUrl
    let utu = that.data.utu
    wx.cloud.callFunction({
      name: 'dynamic_content',
      data: {
        action: "add_comment",
        _id: id,
        content: utu,
        comment_object_id: pid,
        user_info: {
          avatarUrl: ava,
          nickName: name
        }
      }
    }).then(res => {
      wx.showToast({
        title: '评论成功',
        icon: 'none'
      })
      that.setData({
        utu: '',
        uid: ''
      })
      that.xChildReload()
      that.xInit(that.data.id)
    })
  },

  touchStart(e) {
    this.setData({
      startX: e.touches[0].clientX,
      startY: e.touches[0].clientY
    })
  },

  touchStarts(e) {
    this.setData({
      startXs: e.touches[0].clientX,
      startYs: e.touches[0].clientY
    })
  },

  touchMoves(e) {
    let that = this
    let moveX = e.changedTouches[0].clientX;
    let moveY = e.changedTouches[0].clientY;
    let index = e.currentTarget.dataset.index;
    let oindex = e.currentTarget.dataset.oindex
    // 拿到滑动的角度，判断是否大于 30°，若大于，则不滑动
    let angle = this.angle({
      X: this.data.startX,
      // Y: this.data.startY
    }, {
      X: moveX,
      // Y: moveY
    });
    if (angle <= -40) {
      that.setData({
        ['posts.comment_content[' + index + '].sed_comments[' + oindex + '].move']: true,
        uid: ""
      })
    }
  },

  touchMove(e) {
    let that = this
    let moveX = e.changedTouches[0].clientX;
    // let moveY = e.changedTouches[0].clientY;
    let index = e.currentTarget.dataset.index;
    // 拿到滑动的角度，判断是否大于 30°，若大于，则不滑动
    let angle = this.angle({
      X: this.data.startX,
      // Y: this.data.startY
    }, {
      X: moveX,
      // Y: moveY
    });

    if (angle <= -60) {
      that.setData({
        ['posts.comment_content[' + index + '].isTouchMove']: true,
        uid: ""
      })

    }
  },

  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X
    //返回角度 /Math.atan()返回数字的反正切值
    return _X
  },

  xReback: function (e) {
    let that = this
    let index = e.currentTarget.dataset.index
    that.setData({
      ['posts.comment_content[' + index + '].isTouchMove']: false
    })
  },

  xRebacks: function (e) {
    let that = this
    let index = e.currentTarget.dataset.index
    let oindex = e.currentTarget.dataset.oindex
    that.setData({
      ['posts.comment_content[' + index + '].sed_comments[' + oindex + '].move']: false,
      uid: ""
    })
  },

  xDelete: function (e) {
    let that = this
    // let content = e.currentTarget.dataset.content
    let id = e.currentTarget.dataset.id
    wx.showModal({
      content: '确认删除这条留言吗？',
      title: '警告',
      cancelText: '取消',
      confirmText: '确定',
      
      success: (res) => {
        if (res.cancel) {

        } else if (res.confirm) {
          let _id = id
          let _data = {
            is_delete: 1
          }
          wx.cloud.callFunction({
            name: 'dynamic_content',
            data: {
              action: "del_comment",
              _id: that.data.id ,
              comment_id: id
             }
          }).then(res => {
            wx.showToast({
              title: '删除成功',
              icon: 'none'
            })
            that.xChildReload()
            that.xInit(that.data.id)
          })
          // wx.cloud.callFunction({
          //   name: 'dynamic_content',
          //   data: {
          //     action: "del_comment",
          //     _id: id,
          //     comment_id: content
          //   }
          // }).then(res => {
          //   wx.showToast({
          //     title: '删除成功',
          //     icon: 'none'
          //   })
          //   that.xInit(that.data.id)
          // })
        }
      },
      fail: (res) => { },
      complete: (res) => { },
    })

  },
  xDeleteT:function(e){
    let that =this
    let _id = e.currentTarget.dataset.id
    let _data = {
        is_delete:1
    }
    wx.showModal({
      title: '警告',
      content: '确认删除这条帖子吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: (res) => {
        if (res.confirm) {
          wx.cloud.callFunction({
            name: 'dynamic_content',
            data: {
              action: "update_dynamic_content",
              _id: _id,
              dataObj: _data
            }
          }).then(res => {
            wx.navigateBack({
              delta:1
            })
            that.xChildReload()
          })
        }
      }
    })
    
  },
  xToEditUser:function(){
    wx.navigateTo({
      url: '/subuser/pages/personal_information/index',
    })
  },

})